package com.business.action.oa;

import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.business.bean.oa.CalendarBean;
import com.business.bean.oa.ReportDay;
import com.business.bean.system.UserBean;
import com.business.service.oa.CalendarService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.dao.BeanDAO;
import net.sf.rose.jdbc.query.BeanSQL;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.util.DateFormat;
import net.sf.rose.web.util.WebUtils;

/**
 * 日历管理
 * 
 * @author fengjian
 */
@Controller
@RequestMapping("/oa/calendar")
public class CalendarAction {

	/**
	 * 获取某个部门下一整年的日历，如果没有就创建它
	 */
	@ResponseBody
	@RequestMapping("/list.do")
	public PageBean list(HttpServletRequest request, Service service, String year, String departID) {
		PageBean page = new PageBean();
		List<CalendarBean[]> data = new ArrayList<>();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(CalendarBean.class);
		query.setSQL("select * from OA_CALENDAR where departID=? and calendarDate like ? order by calendarDate asc");
		query.addParameter(departID);
		query.addParameter(year + "%");
		List<CalendarBean> list = dao.list();
		Calendar calendar = Calendar.getInstance();
		// 如果存在
		if (list.size() > 0) {
			// 1月1日是星期几，如果不是星期一，那么本周本日前几天加空日历
			Date d = DateFormat.format(list.get(0).getCalendarDate(), "yyyy-MM-dd");
			calendar.setTime(d);
			int count = calendar.get(Calendar.DAY_OF_WEEK) - 2;
			for (int i = 0; i < count; i++) {
				CalendarBean bean = new CalendarBean();
				bean.setDepartID(departID);
				bean.setCalendarDate("");
				list.add(0, bean);
			}
			// 最后一周空的几天也加上空日历
			count = list.size() % 7;
			count = 7 - count;
			for (int i = 0; i < count; i++) {
				CalendarBean bean = new CalendarBean();
				bean.setDepartID(departID);
				bean.setCalendarDate("");
				list.add(bean);
			}
			// 以一周七天为一行单位数据，分装入多行中
			CalendarBean[] beans = null;
			for (int i = 0; i < list.size(); i++) {
				if (i % 7 == 0) {
					beans = new CalendarBean[7];
					data.add(beans);
				}
				beans[i % 7] = list.get(i);
			}
		} else {
			page.setMessage("指定部门的日历没有创建，是否要创建它?");
		}
		page.setData(data);
		return page;
	}

	/**
	 * 创建某个部门指定某一年整年的日历
	 */
	@ResponseBody
	@RequestMapping("/create.do")
	public PageBean createCalendar(Service service, String year, String departID) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(CalendarBean.class);
		query.setSQL("select * from OA_CALENDAR where departID=? and calendarDate like ? order by calendarDate asc");
		query.addParameter(departID);
		query.addParameter(year + "%");
		List<CalendarBean> list = dao.list();
		Calendar calendar = Calendar.getInstance();
		// 如果不存在，就创建
		if (list.size() == 0) {
			calendar.setTime(new Date());
			calendar.set(Calendar.YEAR, Integer.parseInt(year)); // 设置年
			calendar.set(Calendar.MONTH, 0);// 第一个月
			calendar.set(Calendar.DATE, 1);// 第一日
			Date d1 = calendar.getTime();
			calendar.add(Calendar.YEAR, 1);// 往后加一年
			Date d2 = calendar.getTime();
			int count = DateFormat.getDay(d1, d2); // 算出这一年的天数
			calendar.add(Calendar.YEAR, -1);
			for (int i = 0; i < count; i++) {
				CalendarBean bean = new CalendarBean();
				bean.setDepartID(departID);
				bean.setCalendarDate(DateFormat.format(calendar.getTime(), "yyyy-MM-dd"));
				int j = calendar.get(Calendar.DAY_OF_WEEK);
				if (j == Calendar.SATURDAY || j == Calendar.SUNDAY) {
					bean.setDayType("假日");
				} else {
					bean.setDayType("工作日");
				}
				list.add(bean);
				calendar.add(Calendar.DATE, 1);
			}
			query.createBatchInsertSql(list);
			dao.batchUpdate();
			page.setMessage("日历创建成功.");
		} else {
			page.setMessage("日历已经创建了...");
		}
		return page;
	}

	/**
	 * 设置工作日类型
	 */
	@ResponseBody
	@RequestMapping("/saveFestval.do")
	public PageBean saveFestval(Service service, CalendarBean bean) {
		PageBean page = new PageBean();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setSQL("update OA_CALENDAR set dayType=? where departID=? and calendarDate=?");
		query.addParameter(bean.getDayType());
		query.addParameter(bean.getDepartID());
		query.addParameter(bean.getCalendarDate());
		dao.update();
		return page;
	}

	/**
	 * 设置上下班时间
	 */
	@ResponseBody
	@RequestMapping("/save.do")
	public PageBean save(HttpServletRequest request, Service service) throws Exception {
		PageBean page = new PageBean();
		Map<String, Object> map = WebUtils.getRequestData(request);
		String departID = null;
		String startTime = null;
		String endTime = null;
		Date startDate = null;
		Date endDate = null;
		Object obj = map.get("departID");
		if (obj != null) {
			departID = obj.toString();
		}
		obj = map.get("startTime");
		if (obj != null) {
			startTime = obj.toString();
		}
		obj = map.get("endTime");
		if (obj != null) {
			endTime = obj.toString();
		}
		obj = map.get("startDate");
		if (obj != null) {
			startDate = DateFormat.format(obj.toString(), DateFormat.DATE_FORMAT_1);
		}
		obj = map.get("endDate");
		if (obj != null) {
			endDate = DateFormat.format(obj.toString(), DateFormat.DATE_FORMAT_1);
		}
		if (departID == null || startTime == null || endTime == null || startDate == null || endDate == null) {
			page.setSuccess(false);
			page.setMessage("参数：部门、开始日期、结束日期、上班时间、下班时间、休息时长");
			return page;
		}
		int startWorkHour, startWorkMinute = 0;
		if (startTime.indexOf(':') != -1) {
			String[] arr = StringUtils.split(startTime, ':');
			startWorkHour = Integer.parseInt(arr[0]);
			startWorkMinute = Integer.parseInt(arr[1]);
		} else {
			startWorkHour = Integer.parseInt(startTime);
		}
		int endWorkHour, endWorkMinute = 0;
		if (endTime.indexOf(':') != -1) {
			String[] arr = StringUtils.split(endTime, ':');
			endWorkHour = Integer.parseInt(arr[0]);
			endWorkMinute = Integer.parseInt(arr[1]);
		} else {
			endWorkHour = Integer.parseInt(endTime);
		}
		Calendar calendar = Calendar.getInstance();
		List<CalendarBean> list = new ArrayList<>();
		int count = DateFormat.getDay(startDate, endDate);
		calendar.setTime(startDate);
		for (int i = 0; i <= count; i++) {
			CalendarBean bean = new CalendarBean();
			bean.setCalendarDate(DateFormat.format(calendar.getTime(), DateFormat.DATE_FORMAT_1));
			bean.setDepartID(departID);
			bean.setStartWorkHour(startWorkHour);
			bean.setStartWorkMinute(startWorkMinute);
			bean.setEndWorkHour(endWorkHour);
			bean.setEndWorkMinute(endWorkMinute);
			bean.setReleaseTime(Double.parseDouble(map.get("releaseTime").toString()));
			calendar.add(Calendar.DATE, 1);
			list.add(bean);
		}
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(CalendarBean.class);
		StringBuilder sb = new StringBuilder();
		sb.append("update OA_CALENDAR set startWorkHour=#startWorkHour#,startWorkMinute=#startWorkMinute#,");
		sb.append("endWorkHour=#endWorkHour#,endWorkMinute=#endWorkMinute#,releaseTime=#releaseTime# ");
		sb.append("where departID=#departID# and calendarDate=#calendarDate#");
		query.createBatchSql(sb.toString(), list);
		dao.batchUpdate();
		service.commit();
		// 更新员工的工作日报中的上下班时间和休息时长
		query.setEntityClass(UserBean.class);
		query.setSQL("select userID,departID from SYS_USER where status=1 and departID like ? ");
		query.addParameter(departID + "%");
		List<UserBean> users = dao.list();
		sb = new StringBuilder();
		sb.append("update OA_REPORT_DAY set startWorkTime=?,endWorkTime=?,releaseTime=? ");
		sb.append("where userID=? and calendarDate=?");
		PreparedStatement pstmt = service.getConnection().prepareStatement(sb.toString());
		CalendarService cs = new CalendarService();
		for (UserBean u : users) {
			String sDate = DateFormat.format(startDate, DateFormat.DATE_FORMAT_1);
			String eDate = DateFormat.format(endDate, DateFormat.DATE_FORMAT_1);
			List<CalendarBean> calendars = cs.getCalendarBeanList(dao, query, u.getDepartID(), sDate, eDate);
			String deptID = calendars.get(0).getDepartID();
			// 如果此用户的日历排班与此次修改的部门不一致，那么并不受影响，不用更新
			if (!deptID.equals(departID)) {
				continue;
			}
			for (CalendarBean ca : calendars) {
				calendar.setTime(DateFormat.format(ca.getCalendarDate(), DateFormat.DATE_FORMAT_1));
				calendar.set(Calendar.HOUR_OF_DAY, ca.getStartWorkHour());
				calendar.set(Calendar.MINUTE, ca.getStartWorkMinute());
				// System.out.println(DateFormat.format(calendar.getTime(),
				// DateFormat.DATE_FORMAT_3));
				pstmt.setObject(1, new java.sql.Timestamp(calendar.getTime().getTime()));
				calendar.set(Calendar.HOUR_OF_DAY, ca.getEndWorkHour());
				calendar.set(Calendar.MINUTE, ca.getEndWorkMinute());
				pstmt.setObject(2, new java.sql.Timestamp(calendar.getTime().getTime()));
				// System.out.println(DateFormat.format(calendar.getTime(),
				// DateFormat.DATE_FORMAT_3));
				pstmt.setDouble(3, ca.getReleaseTime());
				pstmt.setString(4, u.getUserID());
				pstmt.setString(5, ca.getCalendarDate());
				pstmt.addBatch();
			}
			pstmt.executeBatch();
			service.commit();
		}
		return page;
	}

	/**
	 * 获取某个人的日历
	 */
	@ResponseBody
	@RequestMapping("/user/list.do")
	public PageBean userList(Service service, String year, String userID) {
		PageBean page = new PageBean();
		List<CalendarBean[]> data = new ArrayList<>();
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(ReportDay.class);
		query.setSQL("select * from OA_REPORT_DAY where userID=? and calendarDate like ? order by calendarDate asc");
		query.addParameter(userID);
		query.addParameter(year + "%");
		List<ReportDay> list = dao.list();
		Calendar calendar = Calendar.getInstance();
		// 如果存在
		if (list.size() > 0) {
			List<CalendarBean> calendarList = new ArrayList<>();
			for (ReportDay rd : list) {
				CalendarBean bean = new CalendarBean();
				Date d = rd.getStartWorkTime();
				bean.setStartWorkHour(Integer.parseInt(DateFormat.format(d, "HH")));
				bean.setStartWorkMinute(Integer.parseInt(DateFormat.format(d, "mm")));
				d = rd.getEndWorkTime();
				bean.setEndWorkHour(Integer.parseInt(DateFormat.format(d, "HH")));
				bean.setEndWorkMinute(Integer.parseInt(DateFormat.format(d, "mm")));
				bean.setCalendarDate(rd.getCalendarDate());
				bean.setDayType(rd.getDayType());
				bean.setReleaseTime(rd.getReleaseTime());
				calendarList.add(bean);
			}
			// 1月1日是星期几，如果不是星期一，那么本周本日前几天加空日历
			Date d = DateFormat.format(list.get(0).getCalendarDate(), "yyyy-MM-dd");
			calendar.setTime(d);
			int count = calendar.get(Calendar.DAY_OF_WEEK) - 2;
			for (int i = 0; i < count; i++) {
				CalendarBean bean = new CalendarBean();
				bean.setCalendarDate("");
				calendarList.add(0, bean);
			}
			// 最后一周空的几天也加上空日历
			count = calendarList.size() % 7;
			count = 7 - count;
			for (int i = 0; i < count; i++) {
				CalendarBean bean = new CalendarBean();
				bean.setCalendarDate("");
				calendarList.add(bean);
			}
			// 以一周七天为一行单位数据，分装入多行中
			CalendarBean[] beans = null;
			for (int i = 0; i < calendarList.size(); i++) {
				if (i % 7 == 0) {
					beans = new CalendarBean[7];
					data.add(beans);
				}
				beans[i % 7] = calendarList.get(i);
			}
		} else {
			page.setMessage("指定人员的日历没有创建!");
		}
		page.setData(data);
		return page;
	}

	/**
	 * 设置某些员工列表的工作日历
	 */
	@ResponseBody
	@RequestMapping("/user/set.do")
	public PageBean userSet(HttpServletRequest request, Service service) {
		PageBean page = new PageBean();
		Map<String, Object> map = WebUtils.getRequestData(request);
		String userIDs = null;
		String startTime = null;
		String endTime = null;
		Date startDate = null;
		Date endDate = null;
		Object obj = map.get("startTime");
		if (obj != null) {
			startTime = obj.toString();
		}
		obj = map.get("endTime");
		if (obj != null) {
			endTime = obj.toString();
		}
		obj = map.get("startDate");
		if (obj != null) {
			startDate = DateFormat.format(obj.toString(), DateFormat.DATE_FORMAT_1);
		}
		obj = map.get("endDate");
		if (obj != null) {
			endDate = DateFormat.format(obj.toString(), DateFormat.DATE_FORMAT_1);
		}
		if (startTime == null || endTime == null || startDate == null || endDate == null) {
			page.setSuccess(false);
			page.setMessage("参数：开始日期、结束日期、上班时间、下班时间、休息时长");
			return page;
		}
		obj = map.get("userIDs");
		if (obj != null) {
			userIDs = obj.toString();
		}
		if (userIDs == null) {
			page.setSuccess(false);
			page.setMessage("参数：员工列表不能为空");
			return page;
		}
		int startWorkHour, startWorkMinute = 0;
		if (startTime.indexOf(':') != -1) {
			String[] arr = StringUtils.split(startTime, ':');
			startWorkHour = Integer.parseInt(arr[0]);
			startWorkMinute = Integer.parseInt(arr[1]);
		} else {
			startWorkHour = Integer.parseInt(startTime);
		}
		int endWorkHour, endWorkMinute = 0;
		if (endTime.indexOf(':') != -1) {
			String[] arr = StringUtils.split(endTime, ':');
			endWorkHour = Integer.parseInt(arr[0]);
			endWorkMinute = Integer.parseInt(arr[1]);
		} else {
			endWorkHour = Integer.parseInt(endTime);
		}
		String[] ids = StringUtils.split(userIDs, ',');
		double releaseTime = Double.parseDouble(map.get("releaseTime").toString());
		Calendar calendar = Calendar.getInstance();
		List<ReportDay> list = new ArrayList<>();
		int count = DateFormat.getDay(startDate, endDate);
		calendar.setTime(startDate);
		for (int i = 0; i <= count; i++) {
			for (String userID : ids) {
				ReportDay bean = new ReportDay();
				bean.setUserID(userID);
				calendar.set(Calendar.HOUR_OF_DAY, startWorkHour);
				calendar.set(Calendar.MINUTE, startWorkMinute);
				bean.setCalendarDate(DateFormat.format(calendar.getTime(), DateFormat.DATE_FORMAT_1));
				bean.setStartWorkTime(calendar.getTime());
				calendar.set(Calendar.HOUR_OF_DAY, endWorkHour);
				calendar.set(Calendar.MINUTE, endWorkMinute);
				// 如果开始上班时间大于下班时间,那么下班时间是第二天
				if (startWorkHour > endWorkHour) {
					calendar.add(Calendar.DAY_OF_MONTH, 1);
					bean.setEndWorkTime(calendar.getTime());
					calendar.add(Calendar.DAY_OF_MONTH, -1);
				}else{
					bean.setEndWorkTime(calendar.getTime());
				}
				bean.setReleaseTime(releaseTime);
				list.add(bean);
			}
			calendar.add(Calendar.DATE, 1);
		}
		BeanDAO dao = new BeanDAO(service);
		BeanSQL query = dao.getQuerySQL();
		query.setEntityClass(CalendarBean.class);
		StringBuilder sb = new StringBuilder();
		sb.append("update OA_REPORT_DAY set startWorkTime=#startWorkTime#,endWorkTime=#endWorkTime#,");
		sb.append("releaseTime=#releaseTime# ");
		sb.append("where userID=#userID# and calendarDate=#calendarDate#");
		query.createBatchSql(sb.toString(), list);
		dao.batchUpdate();
		service.commit();
		return page;
	}
}
